package com.yh.csx.crm.core.util;

import com.yh.csx.crm.core.common.AuthFilter;
import com.yh.csx.crm.core.enums.BizError;
import com.yh.csx.crm.core.exception.BusinessException;
import com.yh.b2b.usercenter.facade.stub.vo.UserVO;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Huang Zhaoping
 * @date 2019/1/29
 */
public class WebUtils {

    private static WebContext getWebContext() {
        WebContext context = threadContext.get();
        if (context == null) {
            throw new BusinessException("当前线程未绑定请求上下文");
        }
        return context;
    }

    public static HttpServletRequest getRequest() {
        return getWebContext().request;
    }

    public static HttpServletResponse getResponse() {
        return getWebContext().response;
    }

    private static AuthFilter.Auth getAuth() {
        AuthFilter.Auth auth = getWebContext().auth;
        if (auth == null || !auth.isLogin()) {
            throw new BusinessException(BizError.NOT_LOGIN);
        }
        return auth;
    }

    public static UserVO getUser() {
        return getAuth().getUser();
    }

    public static Long getUserId() {
        return getUser().getId();
    }

    public static String getUserName() {
        return getUser().getName();
    }

    public static String getToken() {
        return getAuth().getToken();
    }

    public static class WebContext {
        private HttpServletRequest request;
        private HttpServletResponse response;
        private AuthFilter.Auth auth;

        public WebContext(HttpServletRequest request, HttpServletResponse response) {
            this.request = request;
            this.response = response;
        }

        public void setAuth(AuthFilter.Auth auth) {
            this.auth = auth;
        }
    }

    private static final ThreadLocal<WebContext> threadContext = new ThreadLocal<>();

    public static void bindContext(WebContext context) {
        threadContext.set(context);
    }

    public static void clearContext() {
        threadContext.remove();
    }

}
